var apple_table_apply = function() {
    var table = window.apple_table_cache.Table;
    if (!table) {
        alert('Referential pricing table is not loaded.');
        return;
    }
    var mtr = document.querySelector('.editAppField div:first-child tr');
    if (!mtr) {
        alert('Android pricing table is not found on this page.');
        return;
    }
    var mcur = mtr.querySelector('td:first-child').innerText.replace(/\s+/g, '');
    var mprice = mtr.querySelector('input').value - 0;
    var map;
    var i;
    for (i=0; i<table.length; i++) {
        var line = table[i];
        if (line[mcur]==mprice) map=line;
    }
    if (! map) {
        alert(mcur+' '+mprice+' is not found on tiers table of '+(table.length)+'.');
        return;
    }
    var cnt = 0;
    var tot = 0;
    var list = document.querySelectorAll('.editAppField tr');
    for (i=0; i<list.length; i++) {
        var tr = list[i];
        var td = tr.querySelector('td:first-child');
        if (! td) continue;
        var input = tr.querySelector('input');
        if (! input) continue;
        var types = input.getAttribute('type');
        if (types != 'text') continue;
        tot ++;
        var cur = td.innerText.replace(/\s+/g, '');
        input.style.backgroundColor = '#FFFFCC';
        if (! map[cur]) continue;
        if (input.value != map[cur]) cnt ++;
        input.style.backgroundColor = '#EEFFFF';
        input.value = map[cur];
    }
    alert(cnt+' / '+tot+' fields updated with prices for Tier: '+map.Tier);
};
window.apple_table_loaded = function(data) {
    window.apple_table_cache = data;
    apple_table_apply();
};
var apple_table_fetch = function() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://kawanet.googlecode.com/svn/trunk/android/market/apple-table.jsonp';
    document.body.appendChild(script);
};
if (location.host != 'market.android.com') {
    location.href = 'https://market.android.com/publish/Home';
} else if (window.apple_table_cache) {
    apple_table_apply();
} else {
    apple_table_fetch();
}
